package gui;

import protocol.generic.AbstractProtocolManager;
import protocol.generic.Group;
import protocol.generic.ProtocolException;

import com.trolltech.qt.core.QObject;
import com.trolltech.qt.core.QSize;
import com.trolltech.qt.gui.QCloseEvent;
import com.trolltech.qt.gui.QDialog;
import com.trolltech.qt.gui.QIcon;
import com.trolltech.qt.gui.QMessageBox;
import com.trolltech.qt.gui.QPixmap;

public class AddEntry extends QDialog{
	MainWindow mw;
	Ui_AddEntry ui=new Ui_AddEntry();
	
	public AddEntry(MainWindow mw){
		super(mw);
		this.mw=mw;
		ui.setupUi(this);
		this.show();
		
		for(AbstractProtocolManager manager : this.mw.protocolManagers){
			QIcon icon;
			if(manager.getProtocol().equalsIgnoreCase("msn"))
				icon=new QIcon(new QPixmap("classpath:resources/msn.png"));
			else if(manager.getProtocol().equalsIgnoreCase("jabber"))
				icon=new QIcon(new QPixmap("classpath:resources/jabber.png"));
			else
				icon=new QIcon(new QPixmap("classpath:resources/google-talk.png"));
			ui.protocolManagerBox.addItem(icon, manager.getUserID()+" ("+manager.getProtocol()+")");
		}
		ui.iconLabel.setPixmap(new QIcon(new QPixmap("classpath:resources/add a buddy.png")).pixmap(new QSize(70,70)));
		ui.protocolManagerBox.activatedIndex.connect(this, "protocolSetted(Integer)");
		ui.protocolManagerBox.activatedIndex.emit(0);
		
	}
	
	public void protocolSetted(Integer index){
		ui.groupBox.clear();
		for(Group group : this.mw.protocolManagers.get(index.intValue()).getGroups()){
			ui.groupBox.addItem(group.getName());
		}
	}
	
	public void accept(){
		String []groups=new String[1];
		groups[0]=ui.groupBox.currentText();
		AbstractProtocolManager manager=this.mw.protocolManagers.get(ui.protocolManagerBox.currentIndex());
		try {
			if(manager.getProtocol().equalsIgnoreCase("yaim")){
				manager.sendSubscriptionRequest(ui.userNameEdit.text());
			}else{
				manager.addEntry(ui.userNameEdit.text(), ui.userAliasEdit.text(), groups);
				this.mw.updateBuddyList();
			}
		} catch (ProtocolException e) {
			e.printStackTrace();
			QMessageBox.critical(this, "add entry failed", "Cannot add this entry");
		}
	}
}
